package com.example.vpn_demo.http2

import android.util.Log
import okhttp3.*
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLSocket

class Http2Handler {
    companion object {
        private const val TAG = "Http2Handler"
    }

    private val client = OkHttpClient.Builder()
        .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .build()

    fun handleConnection(socket: SSLSocket, host: String, requestId: Long) {
        try {
            val request = Request.Builder()
                .url("https://$host")
                .build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: java.io.IOException) {
                    Log.e(TAG, "[$requestId] HTTP/2 请求失败", e)
                }

                override fun onResponse(call: Call, response: Response) {
                    Log.i(TAG, """
                        ┌──────────── HTTP/2 响应 [$requestId] ────────────
                        │ 协议: ${response.protocol}
                        │ 状态码: ${response.code}
                        │ Headers:
                        ${response.headers.joinToString("\n") { "│   ${it.first}: ${it.second}" }}
                        └────────────────────────────────────
                    """.trimIndent())
                    response.close()
                }
            })
        } catch (e: Exception) {
            Log.e(TAG, "[$requestId] 处理 HTTP/2 连接失败", e)
        }
    }
} 